export default class WebSocket {
	
	constructor(uri, headers) {
		this.uri = uri;
		this.isOpen = false;
		this._connect = null;
		
		console.log(JSON.stringify(headers))
		this._connect = uni.connectSocket({
				url: uri,
				headers: headers || {
					'content-type': 'application/json'
				},
				success: () => {
					console.log('success')
				},
				fail: () => {
					console.log('fail')
				},
		});
		
		uni.onSocketOpen((res) => {
			this.isOpen = true;
			if(this.onopen) this.onopen();
		});
		uni.onSocketError(function (res) {
			if(this.onerror) this.onerror();
			console.log('WebSocket连接打开失败，请检查！', JSON.stringify(res));
		});
		
		this._connect.onMessage(res => {
			this.onmessage(res);
		})
	}
	
	close () {
		var close = this.onclose;
		this._connect.close({
			complete: () => {
				if(close) close();
			}
		});
	}
	
	send(data) {
		console.log(data)
		if(!this.isOpen) return;
		this._connect.send({
				data: data
		});
	}
};